package keter.sec.springsec.security;

import keter.sec.springsec.security.handler.FailureHandler;
import keter.sec.springsec.security.handler.SuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
@Profile({"sqlite"})
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired SuccessHandler successHandler;
	@Autowired FailureHandler failureHandler;
    //	@Autowired AjaxFailureHandler failureHandler;
    @Autowired UserDetailsService userDetailsService;
	@Autowired AuthenticationProvider daoAuthenticationProvider;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
	    //开放访问
        http.authorizeRequests().antMatchers("/css/**","/venders/**","/login**").permitAll();
        //管理员
        http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN");
        //普通用户
        http.authorizeRequests().antMatchers("/user/**").hasRole("USER");
        //登录认证
        http
                .csrf().disable()
                .authorizeRequests().anyRequest().fullyAuthenticated().and()
//                .addFilter(new KeterAuthenticationFilter())
//                .addFilterAt(new KeterAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .formLogin().loginProcessingUrl("/authenticate").usernameParameter("username").passwordParameter("password")
                .loginPage("/login").successHandler(successHandler).failureHandler(failureHandler).and()
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider);
    }
}